﻿using System.ComponentModel;
using SourceGrid;
using SourceGrid.Cells.Controllers;

namespace ZeBobo5.LibraryHelper.Core.Grid.Controllers
{
    public class RowFocusChangingController : ControllerBase
    {
        public static readonly RowFocusChangingController Default = new RowFocusChangingController();
        private Position _newPosition = Position.Empty;
        private Position _oldPosition = Position.Empty;

        public override void OnFocusLeaving(CellContext sender, CancelEventArgs e)
        {
            if (_newPosition == Position.Empty)
            {
                return;
            }
            _oldPosition = sender.Position;
            if (sender.Grid is IRowFocusChanging)
            {
                ChangeActivePositionEventArgs arg = 
                    _oldPosition == _newPosition ? 
                    new ChangeActivePositionEventArgs(_oldPosition, Position.Empty) : 
                    new ChangeActivePositionEventArgs(_oldPosition, _newPosition);
                ((IRowFocusChanging) sender.Grid).OnRowFocusChangingEvent(arg);
                e.Cancel = arg.Cancel;
            }
            if (_oldPosition == _newPosition)
            {
                _newPosition = Position.Empty;
            }
            _oldPosition = Position.Empty;
            base.OnFocusLeaving(sender, e);
        }

        public override void OnFocusEntering(CellContext sender, CancelEventArgs e)
        {
            if (sender.Position == Position.Empty)
            {
                return;
            }
            _oldPosition = _newPosition;
            _newPosition = sender.Position;
            if (_oldPosition == Position.Empty)
            {
                if (sender.Grid is IRowFocusChanging)
                {
                    ChangeActivePositionEventArgs arg = new ChangeActivePositionEventArgs(_oldPosition, _newPosition);
                    ((IRowFocusChanging) sender.Grid).OnRowFocusChangingEvent(arg);
                    e.Cancel = arg.Cancel;
                }
            }
            base.OnFocusEntering(sender, e);
        }
    }
}